# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)

option_list <- list(
  make_option("--t", default = "normal", type = "character", help = "normal method"),
  make_option("--ir", default = "", type = "character", help = "inner nomal meta name"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(scipen = 200)

configData <- read.csv(opt$config, header = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

configData

isLoess <- configData["isLoess", "value"] == "T"

data <- read.csv("02_AllMet_Raw_Missing_Value_Filled.csv", header = T, stringsAsFactors = F, row.names = 1) %>%
  rownames_to_column("Raw_Metabolite")

if (isLoess) {
  data <- read_csv("03_AllMet_Raw_NormQCsamples.csv")
}

rate <- 10000
if (opt$t == "normal") {
  data <- data %>%
    mutate_at(vars(-c("Raw_Metabolite")), function(x) {
      sum <- x %>%
        as.numeric() %>%
        sum()
      x * rate / sum
    })
}else {
  index <- which(data$Name == opt$ir)
  data <- data %>%
    mutate_at(vars(-c("Raw_Metabolite")), function(x) {
      x / x[index]
    })
}

outData <- data

head(outData)

write.csv(outData, "03_AllMet_Raw_NormArea.csv", row.names = F)



